package vashion.azeroth.core.sms;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.core.result.ApiResult;

/**
 * @author Reganchen
 *
 */
public class NeteaseSMSSender {

	private String url;
	private String appKey;
	private String appSecret;
	private String nonce;
	private Map<String, Integer> templateMaps;

	/**
	 * 发送通知短信
	 * 
	 * @param mobileArray
	 *            接收者号码列表，Array格式，限制接收者号码个数最多为100个
	 * @param templateName
	 *            模板的名字
	 * @param paramArray
	 *            短信参数列表，用于依次填充模板，Array格式;对于不包含变量的模板，不填此参数表示模板即短信全文内容
	 * @throws Exception
	 */
	public ApiResult<Boolean> sendMSM(String[] mobileArray, String templateName, String[] paramArray) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);// 参考
																					// 计算CheckSum的java代码

		// 设置请求的header
		httpPost.addHeader("AppKey", appKey);
		httpPost.addHeader("Nonce", nonce);
		httpPost.addHeader("CurTime", curTime);
		httpPost.addHeader("CheckSum", checkSum);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("mobiles", stringArray2JSONArray(mobileArray)));
		nvps.add(new BasicNameValuePair("templateid", templateMaps.get(templateName).toString()));
		if (null != paramArray && paramArray.length > 0) {
			nvps.add(new BasicNameValuePair("params", stringArray2JSONArray(paramArray)));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);

			// 解析执行结果
			String sendResponse = EntityUtils.toString(response.getEntity(), "utf-8");
			System.out.println(sendResponse);
			NeteaseSMSSenderResult sendResult = JSON.parseObject(sendResponse, NeteaseSMSSenderResult.class);
			if (200 == sendResult.getCode()) {
				return ApiResult.newSuccessResult();
			} else {
				return ApiResult.newErrorResult(sendResult.getCode(), sendResult.getMsg());
			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(),
					CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
	}

	/**
	 * @param paramArray
	 * @return JSONArray
	 */
	private String stringArray2JSONArray(String[] paramArray) {
		StringBuffer params = new StringBuffer("[");
		for (int i = 0; i < paramArray.length; i++) {
			if (i > 0)
				params.append(",");
			params.append("'").append(paramArray[i]).append("'");
		}
		params.append("]");
		return params.toString();
	}

	/**
	 * 发送通知短信
	 * 
	 * @param mobile
	 *            接收者号码
	 * @param templateName
	 *            模板的名字
	 * @param param
	 *            短信参数，不填此参数表示模板即短信全文内容
	 * @throws Exception
	 */
	public ApiResult<Boolean> sendMSM(String mobile, String templateName, String param) {
		String[] mobileArray = new String[] { mobile };
		String[] paramArray = new String[] { param };
		return this.sendMSM(mobileArray, templateName, paramArray);
	}

	/**
	 * 发送通知短信
	 * 
	 * @param mobile
	 *            接收者号码
	 * @param templateName
	 *            模板的名字
	 * @param paramArray
	 *            短信参数列表，用于依次填充模板，Array格式;对于不包含变量的模板，不填此参数表示模板即短信全文内容
	 * @throws Exception
	 */
	public ApiResult<Boolean> sendMSM(String mobile, String templateName, String[] paramArray) {
		String[] mobileArray = new String[] { mobile };
		return this.sendMSM(mobileArray, templateName, paramArray);
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getAppKey() {
		return appKey;
	}

	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}

	public String getNonce() {
		return nonce;
	}

	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public Map<String, Integer> getTemplateMaps() {
		return templateMaps;
	}

	public void setTemplateMaps(Map<String, Integer> templateMaps) {
		this.templateMaps = templateMaps;
	}

}
